
require 'rexml/document'
require 'rexml/xpath'

module Oos4ruby
class Entry

  def initialize(node)
    if node.class == String
      @element = REXML::Document.new(node, { :raw => nil }).root
    else
      @element = node
    end    
  end

  def to_s
    "<?xml version='1.0' ?>\n" + @element.to_s
  end

  def child(field, namespace = nil)
    if (namespace)
      thisNS = {}
      prefix = 'NS'
      thisNS[prefix] = namespace
    else
      prefix = 'atom'
      thisNS = XmlNamespaces
    end    
    return REXML::XPath.first(@element, "./#{prefix}:#{field}", thisNS)
  end
  
  def add_child(name, prefix = nil, namespace = nil, attr = {})
    name = (prefix || 'atom') + ':' + name
    e = REXML::Element.new( name, @element )
    if prefix && namespace
      e.add_namespace(prefix, namespace) 
    else
      e.add_namespace('atom', AtomNamespace)
    end
    if !attr.empty?
      attr.each_pair { |key, value| e.add_attribute(key.to_s, value) }
    end
    e
  end

  def category( cat )
    first = true
    xpath = "./atom:category["
    if cat[:term]
      xpath += "@term=\"#{cat[:term]}\""
      first = false
    end
    xpath += " and " unless first
    if cat[:scheme]
      xpath += "@scheme=\"#{cat[:scheme]}\""
    end    
    xpath += "]"
    REXML::XPath.first(@element, xpath, XmlNamespaces)
  end
  
  def add_category(term, scheme = nil, label = nil)
    c = @element.add_category(term, scheme, label)    
    c
  end

  def delete_category(c)
    @element.delete_element c
  end
  
  def link(rel)    
    a = REXML::XPath.first(@element, "./atom:link[@rel=\"#{rel}\"]", XmlNamespaces)
    if a      
      uri = URI.parse a.attributes['href']
      if uri.absolute?
        return uri
      else
        return URI.parse(OOS_URL).merge(uri)
      end      
    end    
  end
    
  def match(xp)
    REXML::XPath.match(@element, xp, XmlNamespaces)
  end

  def first(xp)
    REXML::XPath.first(@element, xp, XmlNamespaces)
  end

end
end
